package com.isoftstone.util;

import net.sf.jmimemagic.Magic;
import net.sf.jmimemagic.MagicMatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**

 * 1.通过统一资源定位器（java.net.URL）获取连接器（java.net.URLConnection）
 * 2.设置请求的参数 3.发送请求
 * 4.以输入流的形式获取返回内容
 * 5.关闭输入流
 * @author jswangd
 *
 */
public class HttpUpLoadFile {

    private  static final Logger logger = LoggerFactory.getLogger(HttpUpLoadFile.class);

    /**
     * 多文件上传的方法,同步文件
     *
     * @param actionUrl：上传的路径
     * @param uploadFilePaths：需要上传的文件路径，数组
     * @return
     */



    @SuppressWarnings("finally")
//    public static String uploadFile(String actionUrl, String/*[]*/ uploadFilePaths) {
//        String end = "\r\n";
//        String twoHyphens = "--";
//        String boundary = "*****";
//
//
//        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
//        DataOutputStream ds = null;
//        InputStream inputStream = null;
//        InputStreamReader inputStreamReader = null;
//        BufferedReader reader = null;
//        StringBuffer resultBuffer = new StringBuffer();
//        String tempLine = null;
//
//
//        // 统一资源
//        URL url =null;
//        // 连接类的父类，抽象类
//        URLConnection urlConnection=null ;
//        // http的连接类
//        HttpURLConnection httpURLConnection=null;
//
//        try {
//            url = new URL(actionUrl);
//            urlConnection = url.openConnection();
//            httpURLConnection = (HttpURLConnection) urlConnection;
//
//            // 设置是否从httpUrlConnection读入，默认情况下是true;
//            httpURLConnection.setDoInput(true);
//            // 设置是否向httpUrlConnection输出
//            httpURLConnection.setDoOutput(true);
//            // Post 请求不能使用缓存
//            httpURLConnection.setUseCaches(false);
//            // 设定请求的方法，默认是GET
//            httpURLConnection.setRequestMethod("POST");
//            // 设置字符编码连接参数
//            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
//            // 设置字符编码
//            httpURLConnection.setRequestProperty("Charset", "UTF-8");
//            // 设置请求内容类型
//            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
//
//            String uploadFile = uploadFilePaths/*[i]*/;
//            String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
//
//            /**
//             * 文件名字放到请求中
//             */
//            httpURLConnection.setRequestProperty("filename",filename);
//
//
//            // 设置DataOutputStream
//            ds = new DataOutputStream(httpURLConnection.getOutputStream());
//           /* for (int i = 0; i < uploadFilePaths.length; i++) {*/
//
//
//
//                ds.writeBytes(twoHyphens + boundary + end);
//                ds.writeBytes("Content-Disposition: form-data; " + "name=\"file"/* + i*/ + "\";filename=\"" + filename
//                        + "\"" + end);
//                ds.writeBytes(end);
//                FileInputStream fStream = new FileInputStream(uploadFile);
//                int bufferSize = 1024;
//                byte[] buffer = new byte[bufferSize];
//                int length = -1;
//                while ((length = fStream.read(buffer)) != -1) {
//                    ds.write(buffer, 0, length);
//                }
//                ds.writeBytes(end);
//                /* close streams */
//                fStream.close();
//           // }
//            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
//            /* close streams */
//            ds.flush();
//            if (httpURLConnection.getResponseCode() >= 300) {
//                throw new Exception(
//                        "HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
//            }
//
//            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
//                inputStream = httpURLConnection.getInputStream();
//                inputStreamReader = new InputStreamReader(inputStream);
//                reader = new BufferedReader(inputStreamReader);
//                tempLine = null;
//                resultBuffer = new StringBuffer();
//                while ((tempLine = reader.readLine()) != null) {
//                    resultBuffer.append(tempLine);
//                    resultBuffer.append("\n");
//                }
//            }
//
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } finally {
//            if (ds != null) {
//                try {
//                    ds.close();
//                } catch (IOException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//            if (reader != null) {
//                try {
//                    reader.close();
//                } catch (IOException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//            if (inputStreamReader != null) {
//                try {
//                    inputStreamReader.close();
//                } catch (IOException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//            if (inputStream != null) {
//                try {
//                    inputStream.close();
//                } catch (IOException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
//
//            httpURLConnection.disconnect();
//
//        }
//        return resultBuffer.toString();
//    }
     

    /**
     * 同步文件
     * @param request
     *
     */
    public static void syncFile(HttpServletRequest request,String files,String filepath){

        //获取本地ip
        String localIp = PropertiesUtils.getProperties("loaclIp");


        logger.info("==========================================localip="+localIp);
        //获取ip列表
        String iplist = PropertiesUtils.getProperties("clustiplist");
        //获取同步文件地址
        String uploadfileurl = PropertiesUtils.getProperties("uploadfileurl");
        //是否同步文件1表示同步，0表示不同步文件
        String syncflag = PropertiesUtils.getProperties("syncflag");
            //同步文件
        if ("1".equals(syncflag)) {
            //查到集群列表放入数组
            String[] ips = iplist.split(",");

              if(ips !=null && ips.length>1){

                  for (String clusterip : ips) {


                      /**
                       *  1、如果上传的文件不是本集群,
                       *  2、把文件同步到其他机器身上
                       */
                        //只要上传文件的集群跟本机ip不同，文件同步到其他机器
                      if (!StringUtils.equals(clusterip,localIp)) {
                          uploadfileurl = uploadfileurl.replace("remoteip",clusterip);
                         // uploadFile(uploadfileurl,files);

                          //String filepath = "D:\\workspace\\XINYI\\src\\main\\webapp\\static\\images\\banner-01.png";
                          String urlStr = uploadfileurl;

                          logger.info("uploadfileurl=============="+uploadfileurl);

                          Map<String, String> textMap = new HashMap<String, String>();
                          textMap.put("filepath",filepath);
                          Map<String, String> fileMap = new HashMap<String, String>();
                          fileMap.put("userfile", files); // 掉用的 注解名称 @RequestParam("userfile")
                          String ret = formUpload(urlStr, textMap, fileMap);
                      }
                  }

            }
        }
    }



    /**
     * 同步文件
     * @param urlStr
     * @param textMap
     * @param fileMap
     * @return
     */
    public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {
        String res = "";
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);//设置链接时间5秒
            conn.setReadTimeout(30000);//设置读取时间3秒
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text文本读写
            if (textMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator();//迭代器 读取内容放入Map集合
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());//写入内容
            }

            // file文件读写
            if (fileMap != null) {
                Iterator<Map.Entry<String, String>> iter = fileMap.entrySet().iterator();//迭代器  读取内容放入Map集合
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    File file = new File(inputValue);
                    String filename = file.getName();
                    MagicMatch match = Magic.getMagicMatch(file, false, true);
                    String contentType = match.getMimeType();

                    StringBuffer strBuf = new StringBuffer();//设置buffer流
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

                    out.write(strBuf.toString().getBytes());//写出内容

                    DataInputStream in = new DataInputStream(new FileInputStream(file));//读取文件
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }
            }

            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            // 读取返回数据
            StringBuffer strBuf = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
            res = strBuf.toString();
            reader.close();
            reader = null;
        } catch (Exception e) {
            System.out.println("发送POST请求出错。" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }

    public static void main(String[] args) {
        // 上传文件测试
       // String str = uploadFile("http://127.0.0.1:8080/image/image.do",/*new String[] { "/Users//jswangd/Desktop//1.png",*/"//Users/H__D/Desktop/2.png"/* }*/);

       // System.out.println(str);

    }
}

